package cn.ainit.bj.bjxt;

import cn.ainit.common.ReturnObject;
import cn.ainit.sys.ds.store.StoreService;
import cn.ainit.sys.framework.FrameworkService;
import cn.ainit.sys.framework.save.ReceiveZM;
import cn.ainit.sys.menu.SessionCont;
import cn.ainit.sys.query.datastore.DataStore;
import cn.ainit.sys.query.entity.QueryJson;
import cn.ainit.sys.utils.UUID32;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/bjTopic")
public class BJTopicsController {
	
	private BJTopicsService bjTopicsService;
	private FrameworkService frameworkService;
	private StoreService storeService;

	@Resource
	public void setStoreService(StoreService storeService) {
		this.storeService = storeService;
	}
	
	@Resource
	public void setBjTopicsService(BJTopicsService bjTopicsService) {
		this.bjTopicsService = bjTopicsService;
	}

	@Resource
	public void setFrameworkService(FrameworkService frameworkService) {
		this.frameworkService = frameworkService;
	}

	/***
	 * 第一次保存选题
	 * @param bjTopics
	 * @param request
	 * @return
	 * @throws Exception
	 * @author Xuzq
	 * @date 2014-1-21 下午03:20:30
	 */
	@RequestMapping("/saveTopic")
	@ResponseBody
	public ReturnObject saveOrUpTopic(@RequestBody BJTopics bjTopics,HttpServletRequest request) throws Exception{
		ReturnObject returnObject = new ReturnObject();
		try {
			String bjId = "";
			boolean flag = false;
			if (bjTopics.getXtId() == null || bjTopics.getXtId().equals("")) {
				//新添加，保存
				bjId = UUID32.newGuid();
				bjTopics.setXtId(bjId);
				flag = bjTopicsService.saveTopics(bjTopics);
				if (flag) {
					returnObject.setMsg("success");
					returnObject.setInfo(bjId);
				}else {
					returnObject.setMsg("fail");
				}
			}else{
				//更新
				flag = bjTopicsService.updateTopics(bjTopics);
				if (flag) {
					returnObject.setMsg("upsuccess");
				}else {
					returnObject.setMsg("fail");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			returnObject.setMsg(e.getMessage());
		}
		return returnObject;
	}
	/**
	 * 根据Id得到具体数据
	 * @param id
	 * @param request
	 * @return
	 * @throws Exception
	 * @author wyang
	 * @date : 2014-3-24 下午02:52:15
	 */
	@RequestMapping("/getTopic")
	@ResponseBody
	public BJTopics getBJTopic(String id, HttpServletRequest request) throws Exception{
		try {
			BJTopics topics = this.bjTopicsService.getOneBjTopic(id);
			return topics;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	/**
	 * 把Id传到前台
	 * @param id
	 * @param request
	 * @return
	 * @throws Exception
	 * @author wyang
	 * @date : 2014-3-24 下午02:52:47
	 */
	@RequestMapping("/afferentParam")
	public String afferentParam(String id,HttpServletRequest request) throws Exception{
		try {
			request.setAttribute("id", id);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/pages/topics/topicPlan";
	}
	/**
	 * 传入策划的Id  得到一个立项的实体类
	 * @param xtId
	 * @param request
	 * @return
	 * @throws Exception
	 * @author wyang
	 * @date : 2014-3-24 下午04:32:26
	 */
	@RequestMapping("/planToProject")
	@ResponseBody
	public ReturnObject makeTopic(String xtId,HttpServletRequest request) throws Exception{
		ReturnObject returnObject = new ReturnObject();
		BJTopics topics = new BJTopics();
		try {
			String exlxId = this.bjTopicsService.makeLiXiang(xtId);
			returnObject.setMsg("success");
			returnObject.setInfo(exlxId);
		} catch (Exception e) {
			e.printStackTrace();
			returnObject.setMsg(e.getMessage());
		}
		return returnObject;
	}
	
	
	
	/***
	 * 匹配书目
	 * @param isbnId
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/judgeVerify")
	@ResponseBody
	public ReturnObject judgeStatus(String xtId,String hId,HttpServletRequest request) throws Exception{
		ReturnObject returnObject = new ReturnObject();
		try {
			boolean flag = this.bjTopicsService.piPeiBookList(xtId, hId);
			if (flag==true){
				returnObject.setMsg("书目匹配成功");
			}else {
				returnObject.setMsg("书目匹配失败");
			}
		} catch (Exception e) {
			e.printStackTrace();
			returnObject.setMsg("书目匹配时出现异常");
		}
		return returnObject;
	}
	/**
	 * ISBN&CIP
	 * @param xtId
	 * @param request
	 * @return
	 * @throws Exception
	 * @author wyang
	 * @date : 2014-5-12 下午06:09:28      
	 */
	@RequestMapping("/isbnCipExec")
	@ResponseBody
	public ReturnObject isbnCipExec(String xtId,HttpServletRequest request,HttpSession session) throws Exception{
		ReturnObject returnObject = new ReturnObject();
		try {
			String manId ="";
			Object uid =session.getAttribute(SessionCont.uid);
			if(uid !=null){
				manId = uid.toString();
			}
			String ipId = this.bjTopicsService.isbnCIP(xtId,manId);
			String keyValue = "ISBN_ID-"+ipId;
			returnObject.setMsg("success");
			returnObject.setInfo(keyValue);
		} catch (Exception e) {
			e.printStackTrace();
			returnObject.setMsg("fail");
		}
		return returnObject;
	}
	
	/**
	 * 书稿三审
	 * @param xtId
	 * @param request
	 * @return
	 * @throws Exception
	 * @author wyang
	 * @date : 2014-5-12 下午06:09:28      
	 */
	@RequestMapping("/sanShenExe")
	@ResponseBody
	public ReturnObject sanShenExe(String xtId,HttpServletRequest request,HttpSession session) throws Exception{
		ReturnObject returnObject = new ReturnObject();
		try {
			String manId ="";
			Object uid =session.getAttribute(SessionCont.uid);
			if(uid !=null){
				manId = uid.toString();
			}
			String ipId = this.bjTopicsService.sanShen(xtId,manId);
			String keyValue = "SH_ID-"+ipId;
			returnObject.setMsg("success");
			returnObject.setInfo(keyValue);
		} catch (Exception e) {
			e.printStackTrace();
			returnObject.setMsg("fail");
		}
		return returnObject;
	}
	/**
	 * 开始选题执行按钮
	 * @param xtId
	 * @param request
	 * @return
	 * @throws Exception
	 * @author wyang
	 * @date : 2014-5-23 上午11:41:28
	 */
	@RequestMapping("/beginXT")
	@ResponseBody
	public ReturnObject beginXTPlan(String xtId,int status,HttpServletRequest request,HttpSession session) throws Exception{
		ReturnObject returnObject = new ReturnObject();
		try {
			String valueStr ="";
			String manId ="";
			Object uid =session.getAttribute(SessionCont.uid);
			if(uid !=null){
				manId = uid.toString();
			}
			boolean flag = false;
			if(status == 2){  //执行中（开始执行）
				valueStr = this.bjTopicsService.beginPlan(xtId,manId);
				returnObject.setMsg("success");
				returnObject.setInfo(status+"");
			}else{ //0未启动   1执行完毕   3终止流程 4暂停
				String sql = "update bj_xt v set v.xt_status ='"+status+"' where v.xt_id ='"+xtId+"' ";
				flag = this.bjTopicsService.execSql(sql);
				if(flag){
					returnObject.setMsg("success");
					returnObject.setInfo(status+"");
				}else {
					returnObject.setMsg("fail");
				}
			} 
		} catch (Exception e) {
			e.printStackTrace();
			returnObject.setMsg("fail");
		}
		return returnObject;
	}
	
//	/**
//	 * 判断选题ID是否为有效的选题
//	 * @param xtId
//	 * @param request
//	 * @return
//	 */
//	@RequestMapping("/judgeXtId")
//	@ResponseBody
//	public ReturnObject judgeXtId(String xtId,HttpServletRequest request){
//		boolean flag=false;
//		ReturnObject returnObject = new ReturnObject();
//		try {
//			flag=bjTopicsService.judgeXtId(xtId);
//			returnObject.setFlag(flag);
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//		return returnObject;
//	}
	/**
	 * 判断选题计划按钮当前登陆人是否有点击的权限
	 * @param xtId
	 * @param request
	 * @return
	 */
	@RequestMapping("/judgeXtPlan")
	@ResponseBody
	public String judgeXtPlan(String xtId,HttpServletRequest request,HttpSession session){
		String str  = "";
		String manId = "";
		try {
			Object uid =session.getAttribute(SessionCont.uid);
			if(uid !=null){
				manId = uid.toString();
			}
			str = bjTopicsService.xtPlanRight(xtId, manId);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return str;
	}
	
	/**
	 *根据对象id，获取银行账号
	 * @param xtId
	 * @param request
	 * @return
	 */
	@RequestMapping("/getzhanghaobymanid")
	@ResponseBody
	public List getzhanghaobymanid(String mb,HttpServletRequest request,HttpSession session){
		return bjTopicsService.getzhanghaobymanid(mb);
	}
	
	/**
	 *根据对象id，获取银行账号
	 * @param xtId
	 * @param request
	 * @return
	 */
	@RequestMapping("/getcontractnobymanid")
	@ResponseBody
	public List getcontractnobymanid(String JIAFANG,HttpServletRequest request,HttpSession session){
		return bjTopicsService.getManInfoByManID(JIAFANG);
	}

    @RequestMapping("/getInfobyParty")
    @ResponseBody
    public List getInfobyParty(String XT_NAME,String PAY_PARTY,HttpServletRequest request,HttpSession session){
        return bjTopicsService.getInfobyParty1(XT_NAME,PAY_PARTY);
    }

	/**
	 * 检查是否存在未审核的单据
	 *
	 * @param XT_NAME
	 * @param PAY_PARTY
	 * @param request
	 * @param session
	 * @return
	 */
	@RequestMapping("/checkExistsNotVerifyDj")
    @ResponseBody
    public boolean checkExistsNotVerifyDj(String XT_NAME,String PAY_PARTY,HttpServletRequest request,HttpSession session){
        return bjTopicsService.checkExistsNotVerifyDj(XT_NAME,PAY_PARTY);
    }

	/**
	 * 拉取对账数据
	 *
	 * @param XT_NAME
	 * @param PAY_PARTY
	 * @param request
	 * @param session
	 * @return
	 */
	@RequestMapping("/loadDZInfos")
	@ResponseBody
	public Map loadDZInfos(String dsId, String XT_NAME,String PAY_PARTY,HttpServletRequest request,HttpSession session){
		Map resultMap = new HashMap();
		try {
			DataStore dataStore = frameworkService.getDataStoreById(dsId);
			Object uid = session.getAttribute(SessionCont.uid);
			if (uid == null || "".equals(uid.toString())) {
				System.out.println("用户未登录 FrameworkController L.318");
			}
			String sql = frameworkService.formatSql(dsId, dataStore.getSqlText(), uid == null ? "" : uid.toString());
			String finalSql = "SELECT t1.* from ("+sql+") t1,(select ZZDZ_MONTH from ("+sql+") QUERYTMP " +
					"    WHERE 1 = 1 AND TOPIC_SELECTED = '$TOPIC_SELECTED$' " +
					"          AND PAY_PARTY = '$PAY_PARTY$' " +
					"    GROUP BY ZZDZ_MONTH " +
					"    HAVING count(ZZDZ_MONTH) = 3 " +
					"  ) t2 " +
					"WHERE t1.TOPIC_SELECTED = '$TOPIC_SELECTED$' " +
					"      AND t1.PAY_PARTY = '$PAY_PARTY$' " +
					"      and t1.ZZDZ_MONTH = t2.ZZDZ_MONTH " +
					"ORDER BY t1.ZZDZ_MONTH ASC";

			finalSql = finalSql.replace("$TOPIC_SELECTED$", XT_NAME).replace("$PAY_PARTY$", PAY_PARTY);
			QueryJson tmpQJ = frameworkService.queryRowsBySqlPagination(finalSql, 1, 300);
			List list = tmpQJ.getRows() == null ? new ArrayList() : tmpQJ.getRows();
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
			Calendar calendar = Calendar.getInstance();
			List result = new ArrayList();
			String beginTipMonth = "", endTipMonth = "";
			if(list.size() > 0) {
				Map start = (Map)list.get(0);
				beginTipMonth = start.get("ZZDZ_MONTH").toString();
				calendar.setTime(format.parse(beginTipMonth));
				calendar.add(Calendar.MONTH, 1);
				String next = format.format(calendar.getTime());
				for(int i=0;i<list.size();i++) {
					Map map = (Map)list.get(i);
					if(start.get("ZZDZ_MONTH").toString().equals(map.get("ZZDZ_MONTH").toString())) {
						result.add(map);
					} else if(next.equals(map.get("ZZDZ_MONTH").toString())) {
						result.addAll(list.subList(i, i+3));
						i = i+2;

						calendar = Calendar.getInstance();
						calendar.setTime(format.parse(map.get("ZZDZ_MONTH").toString()));
						calendar.add(Calendar.MONTH, 1);
						next = format.format(calendar.getTime());
					} else {
						break;
					}
				}
				endTipMonth = ((Map)result.get(result.size() - 1)).get("ZZDZ_MONTH").toString();
			}

			resultMap.put("rows", result);

			String tip = "SELECT to_char(min(ZZDZ_MONTH), 'yyyy-MM') minMonth from\n" +
					"  (select to_date(ZZDZ_MONTH, 'yyyy-MM') ZZDZ_MONTH\n" +
					"    FROM ("+sql+") QUERYTMP\n" +
					"    WHERE 1 = 1 AND TOPIC_SELECTED = '"+XT_NAME+"'\n" +
					"          AND PAY_PARTY = '"+PAY_PARTY+"'\n" +
					"    GROUP BY ZZDZ_MONTH\n" +
					"    HAVING count(ZZDZ_MONTH) != 3\n" +
					"  )\n" +
					"WHERE ZZDZ_MONTH <= add_months(sysdate, -2)";

			String cantMonth = frameworkService.execSqlForString(tip);
			String tipStr;
			if(StringUtils.isBlank(beginTipMonth)) {
				tipStr = "无月份可生成对账单。";
			} else {
				tipStr = "可生成"+beginTipMonth+"月 - "+ endTipMonth+"月的对账单。";
			}
			tipStr += cantMonth+"月数据不全，无法生成对账单，请补齐"+cantMonth+"月的数据后再生成对账单！";
			resultMap.put("tipStr", tipStr);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return resultMap;
	}

	/**
	 * 作者对账--执行自动对账
	 * @param PAY_PARTY
	 * @param XT_NAME
	 */
	@RequestMapping("/executeAutoCheckAccount")
	@ResponseBody
	public Map executeAutoCheckAccount(String dsId, String PAY_PARTY, String XT_NAME, String sfct, HttpServletRequest request,HttpSession session) {
		Map map = new HashMap();
		Object uid = session.getAttribute(SessionCont.uid);
		Object staId = session.getAttribute(SessionCont.STATION_ID);
		if (uid == null || "".equals(uid.toString())) {
			System.out.println("用户未登录 FrameworkController L.318");
		}

		boolean exists = bjTopicsService.checkExistsNotVerifyDj(XT_NAME,PAY_PARTY);
		if(exists) {
			map.put("success", false);
			map.put("msg", "该付款对象和选题存在保存未审核单据，请先审核该单据。");
			return map;
		}
		String[] dsIds = dsId.split(";");
		try {
			List<ReturnObject> objs = bjTopicsService.saveAutoCheckAccountInfo(dsIds[1], PAY_PARTY, XT_NAME, sfct, uid, request, session);
			List<Date> months = new ArrayList<>();
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
			SimpleDateFormat print = new SimpleDateFormat("yyyy年MM月");
			String verifyResult = "";
			for(int i=0;i<objs.size();i++) {
				months.add(format.parse(objs.get(i).getInfo()));
			}
			Collections.sort(months);

			map.put("data", objs);
			map.put("success", true);
			map.put("msg", print.format(months.get(0))+"-"+print.format(months.get(months.size()-1)) + "的对账单已生成！");
		} catch (Exception e) {
			map.put("success", false);
			map.put("msg", e.getLocalizedMessage());
		}
		return map;
	}

	public static void main(String[] args) throws ParseException {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
//		System.out.println(format.parse("2017-10"));

		List<Date> a = new ArrayList<>();
		a.add(format.parse("2017-01-01"));
		a.add(format.parse("2017-03-01"));
		a.add(format.parse("2017-02-01"));
		a.add(format.parse("2017-05-01"));
		a.add(format.parse("2017-08-01"));
		a.add(format.parse("2017-06-01"));
		Collections.sort(a);
		System.out.println(a);
	}

	
	@RequestMapping("/getManAccounts")
	@ResponseBody
	public List getManAccounts(String man,HttpServletRequest request,HttpSession session){
		return bjTopicsService.getManAccounts(man);
	}
	
	@RequestMapping("/getXtYinCi")
	@ResponseBody
	public List getXtYinCi(String xtId,String yinCi, HttpServletRequest request,HttpSession session){
		return bjTopicsService.getXtYinCi(xtId,yinCi);
	}
	
	@RequestMapping("/getBSMoney")
	@ResponseBody
	public List getBSMoney(String xtId,String manID,String contract_TYPE,String type,HttpServletRequest request,HttpSession session){
		return bjTopicsService.getBSMoney(xtId,manID,contract_TYPE,type);
	}

    @RequestMapping("/getZZBSMoney")
    @ResponseBody
    public List getZZBSMoney(String xtId,String manID,HttpServletRequest request,HttpSession session){
        return bjTopicsService.getZZBSMoney(xtId,manID);
    }

//    @RequestMapping("/getZZJTBSMoney")
//    @ResponseBody
//        public List getZZJTBSMoney(String sinid,HttpServletRequest request,HttpSession session){
//        return bjTopicsService.getZZJTBSMoney(sinid);
//    }

    @RequestMapping("/getzzJTBM")
    @ResponseBody
    public List<String> getzzJTBM(@RequestBody List<String> runIds,HttpServletRequest request,HttpSession session) throws Exception{
        return this.bjTopicsService.getzzJTBM(runIds);
    }
    @RequestMapping("/getzzJTBMTWO")
    @ResponseBody
    public List<String> getzzJTBMTWO(@RequestBody List<String> runIds,HttpServletRequest request,HttpSession session) throws Exception{
        return this.bjTopicsService.getzzJTBMTWO(runIds);
    }

	
	@RequestMapping("/getNowOidMan")
	@ResponseBody
	public List getNowOidMan(HttpServletRequest request,HttpSession session){
		Object uid = session.getAttribute(SessionCont.uid);
		String oid=uid.toString();
		return bjTopicsService.getNowOidMan(oid);
	}
	
	@RequestMapping("/getNextYinci")
	@ResponseBody
	public List getNextYinci(String xtId,String manID,String contract_TYPE,String yinci,HttpServletRequest request,HttpSession session){
		return bjTopicsService.getNextYinci(xtId,manID,contract_TYPE,yinci);
	}
	
	@RequestMapping("/getNextYinciVerify")
	@ResponseBody
	public List getNextYinciVerify(String xtId,String manID,HttpServletRequest request,HttpSession session){
		return bjTopicsService.getNextYinciVerify(xtId,manID);
	}
	@RequestMapping("/getBookDelYinci")
	@ResponseBody
	public int getBookDelYinci(String xtId,String manID,String yinci,int number,HttpServletRequest request,HttpSession session){
		return bjTopicsService.getBookDelYinci(xtId,manID,yinci,number);
	}
	
	@RequestMapping("/getIsOrSave")
	@ResponseBody
	public List getIsOrSave(String xtId,String manID,String yinci,int number,HttpServletRequest request,HttpSession session){
		return bjTopicsService.getIsOrSave(xtId,manID,yinci,number);
	}
	
	@RequestMapping("/getXtInfo")
	@ResponseBody
	public List getXtInfo(String xtId,String yinci,HttpServletRequest request,HttpSession session){
		return bjTopicsService.getXtInfo(xtId,yinci);
	}
	
	@RequestMapping("/getPubMoney")
	@ResponseBody
	public List getPubMoney(String XT_PUB_ID,HttpServletRequest request,HttpSession session){
		return bjTopicsService.getPubMoney(XT_PUB_ID);
	}
	
	@RequestMapping("/getTrueContra")
	@ResponseBody
	public List getTrueContra(String xtId,String manID,HttpServletRequest request,HttpSession session){
		return bjTopicsService.getTrueContra(xtId,manID);
	}
	
	@RequestMapping("/getDJtypeByc")
	@ResponseBody
	public List getDJtypeByc(String xtId,String manID,String contract_TYPE,HttpServletRequest request,HttpSession session){
		return bjTopicsService.getDJtypeByc(xtId,manID,contract_TYPE);
	}

    @RequestMapping("/getDJtypeByz")
    @ResponseBody
    public List getDJtypeByz(String xtId,String manID,String TYPE_TICKET,HttpServletRequest request,HttpSession session){
        return bjTopicsService.getDJtypeByz(xtId,manID, TYPE_TICKET);
    }
	
	@RequestMapping("/getJTBM")
	@ResponseBody
	public List<String> getJTBM(@RequestBody List<String> runIds,HttpServletRequest request,HttpSession session) throws Exception{
		return this.bjTopicsService.getJTBM(runIds);
	}
	
	@RequestMapping("/getJTBMTWO")
	@ResponseBody
	public List<String> getJTBMTWO(@RequestBody List<String> runIds,HttpServletRequest request,HttpSession session) throws Exception{
		return this.bjTopicsService.getJTBMTWO(runIds);
	}
	
	@RequestMapping("/getAnyAccount")
	@ResponseBody
	public List getAnyAccount(String mb,HttpServletRequest request,HttpSession session){
		return bjTopicsService.getAnyAccount(mb);
	}
	
	@RequestMapping("/getAllMoney")
	@ResponseBody
	public List getAllMoney(String mb,HttpServletRequest request,HttpSession session){
		return bjTopicsService.getAllMoney(mb);
	}
	/**
	 *根据对象id，获取银行账号
	 * @param mb
	 * @param request
	 * @return
	 */
	@RequestMapping("/getzhanghaobyoid")
	@ResponseBody
	public List getzhanghaobyoid(String mb,HttpServletRequest request,HttpSession session){
  
		return bjTopicsService.getzhanghaobyoid(mb);
	}

    @RequestMapping("/getamount")
    @ResponseBody
    public List getamount(String PAY_PARTY, String BASIS_ACCOUNT, String TOPIC_SELECTED,HttpServletRequest request,HttpSession session){

        return bjTopicsService.getamount(PAY_PARTY,BASIS_ACCOUNT,TOPIC_SELECTED);
    }


    /**
     *根据选题ID，获取该选题的营销预算余额
     * @param xt_id
     * @param request
     * @return
     */
    @RequestMapping("/getMarketAmount")
    @ResponseBody
    public double getMarketAmount(String xt_id,HttpServletRequest request,HttpSession session){

        return bjTopicsService.getMarketAmount(xt_id);
    }

    @RequestMapping("/get_zzdata")
    @ResponseBody
    public List get_zzdata(String CWZZ_ID, String PAY_PARTY, String BASIS_ACCOUNT, String TOPIC_SELECTED,HttpServletRequest request,HttpSession session){

        return bjTopicsService.get_zzdata(CWZZ_ID, PAY_PARTY, BASIS_ACCOUNT, TOPIC_SELECTED);
    }

}
